package com.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.bean.Employee;
import com.ssm.bean.Msg;
import com.ssm.service.interfaces.IEmployeeSV;
import com.ssm.utils.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright: Copyright (c) 2018/1/2
 * Description:
 * CLASS_NAME: EmployeeController
 * PACKAGE_NAME: com.ssm.controller
 * version: v1.0.0
 * author: Jin Biao
 * date: 2018/1/2 17:37
 */
@Controller
public class EmployeeController {

    @Autowired
    IEmployeeSV employeeSV;

    /** @method_name:
    * @param:
    * @description: 分页查询
    * @create_user: Jin Biao
    * @create_date: 2018/1/2
    * @create_time: 19:39
    **/
    @RequestMapping("/getEmployee")
    public String getAllEmployee(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum, Model model) throws Exception {

        //查询之前调用这个方法
        PageHelper.startPage(pageNum, Constant.PAGE_SIZE);
        //startPage后面的紧跟着的查询就是分页查询
        List<Employee> allEmployee = employeeSV.getAllEmployee();
        //使用pageInfo封装查询后的信息
        PageInfo pageInfo = new PageInfo(allEmployee,Constant.SHOW_PAGE_SIZE);
        model.addAttribute("pageInfo",pageInfo);
        return "employeeList";

    }

    /** @method_name:  getAllEmployeeInfo
    * @param:  int pageNum ：当前页码   Model model
    * @description: 获取所有员工的信息，附带分页查询
    * @create_user: Jin Biao
    * @create_date: 2018/1/30
    * @create_time: 10:58
    **/
    @RequestMapping("/getAllEmployeeInfo")
    public String getAllEmployeeInfo(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,Model model) throws Exception{
        //查询之前调用这个方法
        PageHelper.startPage(pageNum, Constant.PAGE_SIZE);
        //startPage后面的紧跟着的查询就是分页查询
        List<Employee> allEmployee = employeeSV.getAllEmployeeWithDept();
        //使用pageInfo封装查询后的信息
        PageInfo pageInfo = new PageInfo(allEmployee,Constant.SHOW_PAGE_SIZE);
        model.addAttribute("pageInfo",pageInfo);
        return "employeeList";
    }

    /** @method_name:  getEmployeeToJSON
    * @param:  pageNum 当前页码
    * @description: 将查询结果以json的格式返回给浏览器
    * @create_user: Jin Biao
    * @create_date: 2018/1/4
    * @create_time: 20:34
    **/
    @RequestMapping("/getEmpToJSON")
    @ResponseBody
    public Msg getEmployeeToJSON(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum) throws Exception {
        //查询之前调用这个方法
        PageHelper.startPage(pageNum, Constant.PAGE_SIZE);
        //startPage后面的紧跟着的查询就是分页查询
        List<Employee> allEmployee = employeeSV.getAllEmployeeWithDept();
        //使用pageInfo封装查询后的信息
        PageInfo pageInfo = new PageInfo(allEmployee,Constant.SHOW_PAGE_SIZE);
        return Msg.success().add("pageInfo",pageInfo);
    }

    /** @method_name:  saveEmployee
    * @param:  Employee
    * @description: 保存员工信息
    * @create_user: Jin Biao
    * @create_date: 2018/1/24
    * @create_time: 17:41
    **/
    @RequestMapping(value = "/saveEmployee",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmployee(@Valid Employee employee, BindingResult result) throws Exception{

        if (employee != null) {
            //后端校验
            if(result.hasErrors()){
                List<FieldError> fieldErrors = result.getFieldErrors();
                Map<String,Object> errorMap = new HashMap<>();
                for(FieldError fieldError : fieldErrors){
                    errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
                }
                return Msg.fail().add("errorMap",errorMap);
            }else{
                employeeSV.saveEmployee(employee);
                return Msg.success();
            }
        }else{
            return Msg.fail();
        }
    }

    /** @method_name:  checkEmployee
    * @param:  String empName
    * @param: 若用户名存在，返回sucess,returnCode = 1;否则返回fail，returnCode = 0
    * @description: 校验用户名是否存在
    * @create_user: Jin Biao
    * @create_date: 2018/1/26
    * @create_time: 11:16
    **/
    @ResponseBody
    @RequestMapping("/checkEmployee")
    public Msg checkEmployee(@RequestParam("empName") String empName) throws Exception{

        //增加后端的用户名合法性校验
        String regex = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5}$)";

        if(StringUtils.isNotBlank(empName) && StringUtils.isNoneEmpty(empName)){
            if(!empName.matches(regex)){
                return Msg.fail().add("vailInfo","用户名6-16位由数字和字母构成，或者由2-5位汉字构成");
            }

            boolean isExist = employeeSV.checkEmployee(empName);
            if (isExist){
                return Msg.success();
            }else{
                return Msg.fail().add("vailInfo","用户名已存在！").add("errorType","userName");
            }
        }else{
            return Msg.fail().add("vailInfo","用户名不能为空！");
        }
    }

    /** @method_name:  getEmpById
    * @param:  int empId
    * @description: 根据员工id查询员工的信息
    * @create_user: Jin Biao
    * @create_date: 2018/1/29
    * @create_time: 16:55
    **/
    @RequestMapping(value = "/getEmpById/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmpById(@PathVariable("id")int empId) throws Exception{
        if(empId > 0){
            Employee employee = employeeSV.getEmpById(empId);
            return Msg.success().add("employee",employee);
        }else{
            return Msg.fail();
        }
    }

    /** @method_name:  updateEmployeeById
    * @param:  Employee employee
    * @description: 根据员工的id更新员工信息
    * @create_user: Jin Biao
    * @create_date: 2018/1/30
    * @create_time: 16:35
    **/
    @RequestMapping(value = "/updateEmployee/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateEmployeeById(Employee employee) throws Exception {

            System.out.println(employee);
            employeeSV.updateEmployee(employee);
            return Msg.success();
    }

    /** @method_name: deleteEmpById
    * @param:
    * @description:
    * @create_user: Jin Biao
    * @create_date: 2018/1/30
    * @create_time: 16:36
    **/
    @RequestMapping(value = "/emp/{empId}", method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmpById(@PathVariable("empId")String empIdStr) throws Exception{
        if(empIdStr.contains("-")){
            String[] empIds = empIdStr.split("-");
            employeeSV.deleteEmpBath(empIds);
        }else{
            employeeSV.deleteEmpById(Integer.parseInt(empIdStr));
        }
        return Msg.success();
    }


}
